package com.sam.core.util.json;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.sam.core.Constants;

/**
 * Date对象转化为Json字符串
 * @project EMan
 * @author Sam
 * @version
 * @date Mar 25, 2009 3:13:38 PM
 */
public class DateJsonValueProcessor implements JsonValueProcessor {
	private String format = Constants.DATE_TIME_FORMAT;

	public DateJsonValueProcessor() {

	}

	public DateJsonValueProcessor(String format) {
		this.format = format;
	}

	public String getFormat() {
		return format;
	} 
	/**
	 * 解析Array时间对象
	 */
	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		String[] obj = {};
		if (value instanceof Date[]) {
			SimpleDateFormat sf = new SimpleDateFormat(format);
			Date[] dates = (Date[]) value;
			obj = new String[dates.length];
			for (int i = 0; i < dates.length; i++) {
				obj[i] = sf.format(dates[i]);
			}
		}
		return obj;
	}
	/**
	 * 解析时间对象
	 */
	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		if(value == null){
			return "";
		}
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value.toString();
	}

	public void setFormat(String format) {
		this.format = format;
	}

}